﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using Csla;
using Csla.Security;

using FluentAssertions;

using Haushaltsbuch.DataAcces;
using Haushaltsbuch.DataAcces.Entities;
using Haushaltsbuch.Domain.Authentication;
using Haushaltsbuch.Helpers;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Haushaltsbuch.Tests
{
    [TestClass]
    public class AuthenticationTests
    {
        [TestCleanup] public void TestCleanup()
        {
            HaushaltsbuchPrincipal.Logout();
        }
        [ClassInitialize] public static void Initialize(TestContext context)
        {
           TestHelpers.InitDbForTest();
        }
        
        [TestMethod] public void Login_Sets_AppContext_To_Current_User()
        {
            HaushaltsbuchPrincipal.Login("Admin", "test");

            ApplicationContext.User.Identity.IsAuthenticated.Should().BeTrue();
            ApplicationContext.User.Identity.Name.Should().Be("Admin");

            Thread.CurrentPrincipal.Identity.Should().Be(ApplicationContext.User.Identity);
        }
        [TestMethod] public void Invalid_Password()
        {
            HaushaltsbuchPrincipal.Login("Admin", "test1");

            ApplicationContext.User.Identity.IsAuthenticated.Should().BeFalse();
            ApplicationContext.User.Identity.Should().BeOfType<UnauthenticatedIdentity>();

            Thread.CurrentPrincipal.Identity.Should().BeOfType<UnauthenticatedIdentity>();
        }
        [TestMethod] public void Is_in_Role()
        {
            HaushaltsbuchPrincipal.Login("Admin", "test");

            ApplicationContext.User.Identity.IsAuthenticated.Should().BeTrue();
            ApplicationContext.User.IsInRole("Admin").Should().BeTrue();

            Thread.CurrentPrincipal.IsInRole("Admin").Should().BeTrue();
        }
        [TestMethod] public void Logout_a_User()
        {
            HaushaltsbuchPrincipal.Login("Admin", "test");
            HaushaltsbuchPrincipal.Logout();

            ApplicationContext.User.Identity.IsAuthenticated.Should().BeFalse();
            ApplicationContext.User.Identity.Should().BeOfType<UnauthenticatedIdentity>();

            Thread.CurrentPrincipal.Identity.Should().BeOfType<UnauthenticatedIdentity>();
        }



    }
}
